import time

import asyncio

import aiohttp
import requests

# 同步 sync
# 异步 async

# # 同步操作
# start = time.time()
# print(1)
# time.sleep(1)
# print(2)
# time.sleep(1)
# end = time.time() - start
# print(end)

# # 异步操作
# async def main():
#     start = time.time()
#     print(1)
#     await asyncio.sleep(2)
#     print(2)
#     end = time.time() - start
#     print(end)
#
# main_task = main()
#
# r = asyncio.run(main_task)
# print(r)

# # 多个异步任务并行执行
# async def main1(param):
#     print(param, 'start1')
#     await asyncio.sleep(3)
#     print(param, 'end1')
#
# async def main2(param):
#     print(param, 'start2')
#     await asyncio.sleep(5)
#     print(param, 'end2')
#
# async def main():
#     await asyncio.gather(main1(100), main2(200))
#
# start = time.time()
# asyncio.run(main())
# end = time.time()
# print(end - start)


# async def task(name):
#     await asyncio.sleep(1)
#     print(f'task{name}完成')
#
# async def main():
#     tasks = [task(i) for i in range(10)]
#     await asyncio.gather(*tasks)
#
# asyncio.run(main())
#
# async def main():
#     # 返回异步上下文
#     async with aiohttp.ClientSession() as session:
#         async with session.get('https://httpbin.org/get?age=1') as response:
#             r = await response.json()
#             print(r)
#
# start = time.time()
# asyncio.run(main())
# print(time.time()-start)

# 同步请求10个url
urls = [f'https://httpbin.org/get?age={i}' for i in range(10)]
start = time.time()
for url in urls:
    response = requests.get(url)
    print(response.json())

end = time.time()
print(end-start)

# 异步请求10个url
async def task(name):
    await asyncio.sleep(1)
    print(f'task{name}完成')

# 协程 :把session单独拿出
async def fetch(session,url):
    async with session.get(url) as response:
        return await response.json()

async def main():
    tasks = [task(i) for i in range(10)]
    await asyncio.gather(*tasks)
    async with aiohttp.ClientSession() as session:
        # gather 并行执行多个协程 *[task1(), task2()]
        result = await asyncio.gather(*[fetch(session,f'https://httpbin.org/get?age={i}') for i in range(10)])
        for r in result:
            print(r)

start = time.time()
asyncio.run(main())
print(time.time()-start)